// =============================================
// Docker & Nginx 配置编辑器 - 主脚本文件
// 功能：初始化代码编辑器、处理模板预览、切换视图等
// =============================================

// 模板数据容器
const templates = {
    compose: composeTemplates,
    dockerfile: dockerfileTemplates,
    nginx: nginxTemplates
};

// DOM 元素引用
const composeEditorElement = document.getElementById('compose-editor');
const dockerfileEditorElement = document.getElementById('dockerfile-editor');
const nginxEditorElement = document.getElementById('nginx-editor');
const viewTabs = document.querySelectorAll('.view-tab');
const editorViews = document.querySelectorAll('.editor-view');
const templatePreview = document.getElementById('template-preview');
const previewTitle = document.getElementById('preview-title');
const previewContent = document.getElementById('preview-content');
const cancelPreviewBtn = document.getElementById('cancel-preview');
const applyTemplateBtn = document.getElementById('apply-template');
const changeWallpaperBtn = document.getElementById('change-wallpaper');
const themeSwitcher = document.getElementById('theme-switcher');
const body = document.body;
const composeTemplatesContainer = document.getElementById('compose-templates-container');
const dockerfileTemplatesContainer = document.getElementById('dockerfile-templates-container');
const nginxTemplatesContainer = document.getElementById('nginx-templates-container');
const composeParametersContainer = document.getElementById('compose-parameters-container');
const dockerfileParametersContainer = document.getElementById('dockerfile-parameters-container');
const nginxParametersContainer = document.getElementById('nginx-parameters-container');
const editorActionButtons = document.querySelectorAll('.btn-editor-action');

// 代码编辑器实例
let composeEditor, dockerfileEditor, nginxEditor;

// 当前选中的编辑器类型和模板
let currentEditorType = 'compose';
let currentTemplate = null;

// 编辑器初始化状态
let editorsInitialized = {
    compose: false,
    dockerfile: false,
    nginx: false
};

// 壁纸配置
const wallpapers = [
    'url(https://api.mobufan.eu.org:666/)',
    'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
    'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
    'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
    'linear-gradient(135deg, #fa709a 0%, #fee140 100%)'
];
let currentWallpaperIndex = 0;

// 自动保存间隔（毫秒）
const AUTO_SAVE_INTERVAL = 2000;
let autoSaveTimer = null;

/**
 * 初始化代码编辑器
 * 只初始化当前可见的编辑器以优化性能
 */
function initCodeEditors() {
    initComposeEditor();
}

/**
 * 初始化Docker Compose编辑器
 */
function initComposeEditor() {
    if (editorsInitialized.compose) return;
    
    composeEditor = CodeMirror.fromTextArea(composeEditorElement, {
        mode: 'yaml',
        theme: 'dracula',
        lineNumbers: true,
        indentUnit: 2,
        smartIndent: true,
        indentWithTabs: false,
        electricChars: true,
        autoCloseBrackets: true,
        matchBrackets: true,
        extraKeys: {
            "Ctrl-Space": "autocomplete"
        }
    });
    
    // 从本地存储加载内容
    const savedContent = localStorage.getItem('composeEditorContent');
    composeEditor.setValue(savedContent || '');
    editorsInitialized.compose = true;
    
    // 设置自动保存
    composeEditor.on('change', () => {
        debounceSave('compose', composeEditor.getValue());
    });
    
    setTimeout(() => {
        composeEditor.focus();
    }, 100);
}

/**
 * 初始化Dockerfile编辑器
 */
function initDockerfileEditor() {
    if (editorsInitialized.dockerfile) return;
    
    dockerfileEditor = CodeMirror.fromTextArea(dockerfileEditorElement, {
        mode: 'dockerfile',
        theme: 'dracula',
        lineNumbers: true,
        indentUnit: 4,
        electricChars: true,
        autoCloseBrackets: true
    });
    
    // 从本地存储加载内容
    const savedContent = localStorage.getItem('dockerfileEditorContent');
    dockerfileEditor.setValue(savedContent || '');
    editorsInitialized.dockerfile = true;
    
    // 设置自动保存
    dockerfileEditor.on('change', () => {
        debounceSave('dockerfile', dockerfileEditor.getValue());
    });
    
    setTimeout(() => {
        dockerfileEditor.focus();
    }, 100);
}

/**
 * 初始化Nginx编辑器
 */
function initNginxEditor() {
    if (editorsInitialized.nginx) return;
    
    nginxEditor = CodeMirror.fromTextArea(nginxEditorElement, {
        mode: 'nginx',
        theme: 'dracula',
        lineNumbers: true,
        indentUnit: 4,
        electricChars: true,
        autoCloseBrackets: true
    });
    
    // 从本地存储加载内容
    const savedContent = localStorage.getItem('nginxEditorContent');
    nginxEditor.setValue(savedContent || '');
    editorsInitialized.nginx = true;
    
    // 设置自动保存
    nginxEditor.on('change', () => {
        debounceSave('nginx', nginxEditor.getValue());
    });
    
    setTimeout(() => {
        nginxEditor.focus();
    }, 100);
}

/**
 * 防抖保存函数
 * @param {string} editorType - 编辑器类型
 * @param {string} content - 编辑器内容
 */
function debounceSave(editorType, content) {
    if (autoSaveTimer) {
        clearTimeout(autoSaveTimer);
    }
    
    autoSaveTimer = setTimeout(() => {
        saveEditorContentToStorage(editorType, content);
    }, AUTO_SAVE_INTERVAL);
}

/**
 * 保存编辑器内容到本地存储
 * @param {string} editorType - 编辑器类型
 * @param {string} content - 编辑器内容
 */
function saveEditorContentToStorage(editorType, content) {
    localStorage.setItem(`${editorType}EditorContent`, content);
}

/**
 * 刷新编辑器视图
 * @param {string} editorType - 编辑器类型
 */
function refreshEditor(editorType) {
    setTimeout(() => {
        if (editorType === 'compose' && composeEditor) {
            composeEditor.refresh();
        } else if (editorType === 'dockerfile' && dockerfileEditor) {
            dockerfileEditor.refresh();
        } else if (editorType === 'nginx' && nginxEditor) {
            nginxEditor.refresh();
        }
    }, 100);
}

/**
 * 初始化主题
 */
function initTheme() {
    const savedTheme = localStorage.getItem('theme') || 'dark-mode';
    body.className = savedTheme;
    updateThemeButton(savedTheme);
    
    const editorTheme = savedTheme === 'dark-mode' ? 'dracula' : 'default';
    if (composeEditor) composeEditor.setOption('theme', editorTheme);
    if (dockerfileEditor) dockerfileEditor.setOption('theme', editorTheme);
    if (nginxEditor) nginxEditor.setOption('theme', editorTheme);
}

/**
 * 初始化壁纸
 */
function initWallpaper() {
    const savedWallpaperIndex = localStorage.getItem('wallpaperIndex');
    if (savedWallpaperIndex !== null) {
        currentWallpaperIndex = parseInt(savedWallpaperIndex);
    }
    
    document.body.style.backgroundImage = wallpapers[currentWallpaperIndex];
    document.body.style.backgroundSize = 'cover';
    document.body.style.backgroundRepeat = 'no-repeat';
    document.body.style.backgroundPosition = 'center center';
}

/**
 * 更新主题按钮文本和图标
 * @param {string} theme - 当前主题
 */
function updateThemeButton(theme) {
    const themeIcon = themeSwitcher.querySelector('.theme-icon');
    if (theme === 'dark-mode') {
        themeSwitcher.innerHTML = '<span class="theme-icon"><i class="fas fa-sun"></i></span> 亮色模式';
    } else {
        themeSwitcher.innerHTML = '<span class="theme-icon"><i class="fas fa-moon"></i></span> 暗色模式';
    }
}

/**
 * 切换编辑器视图
 * @param {string} viewType - 视图类型
 */
function switchView(viewType) {
    viewTabs.forEach(tab => {
        if (tab.dataset.view === viewType) {
            tab.classList.add('active');
        } else {
            tab.classList.remove('active');
        }
    });
    
    editorViews.forEach(view => {
        if (view.id === `${viewType}-view`) {
            view.classList.add('active');
            
            if (viewType === 'compose') {
                initComposeEditor();
            } else if (viewType === 'dockerfile') {
                initDockerfileEditor();
            } else if (viewType === 'nginx') {
                initNginxEditor();
            }
            
            refreshEditor(viewType);
            
            setTimeout(() => {
                if (viewType === 'compose' && composeEditor) {
                    composeEditor.focus();
                } else if (viewType === 'dockerfile' && dockerfileEditor) {
                    dockerfileEditor.focus();
                } else if (viewType === 'nginx' && nginxEditor) {
                    nginxEditor.focus();
                }
            }, 200);
        } else {
            view.classList.remove('active');
        }
    });
    
    currentEditorType = viewType;
}

/**
 * 显示模板预览
 * @param {string} type - 模板类型
 * @param {string} templateKey - 模板键名
 */
function showTemplatePreview(type, templateKey) {
    const template = templates[type][templateKey];
    if (!template) return;
    
    currentTemplate = { type, key: templateKey };
    previewTitle.textContent = template.name;
    previewContent.textContent = template.content;
    templatePreview.classList.add('active');
}

/**
 * 应用选中的模板到编辑器
 */
function applyTemplate() {
    if (!currentTemplate) return;
    
    const template = templates[currentTemplate.type][currentTemplate.key];
    if (template) {
        if (currentTemplate.type === 'compose') {
            composeEditor.setValue(template.content);
            saveEditorContentToStorage('compose', template.content);
            composeEditor.focus();
        } else if (currentTemplate.type === 'dockerfile') {
            dockerfileEditor.setValue(template.content);
            saveEditorContentToStorage('dockerfile', template.content);
            dockerfileEditor.focus();
        } else if (currentTemplate.type === 'nginx') {
            nginxEditor.setValue(template.content);
            saveEditorContentToStorage('nginx', template.content);
            nginxEditor.focus();
        }
    }
    
    templatePreview.classList.remove('active');
    currentTemplate = null;
    
    showNotification('模板已成功应用！');
}

/**
 * 显示通知消息
 * @param {string} message - 消息内容
 * @param {string} type - 消息类型
 */
function showNotification(message, type = 'success') {
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.classList.add('show');
    }, 100);
    
    setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

/**
 * 添加参数到编辑器
 * @param {string} command - 要添加的命令
 */
function addParameterToEditor(command) {
    let editor;
    if (currentEditorType === 'compose') {
        editor = composeEditor;
    } else if (currentEditorType === 'dockerfile') {
        editor = dockerfileEditor;
    } else if (currentEditorType === 'nginx') {
        editor = nginxEditor;
    }
    
    if (!editor) return;
    
    const doc = editor.getDoc();
    const cursor = doc.getCursor();
    
    doc.replaceRange(command + '\n', cursor);
    
    showNotification('参数已添加到编辑器');
}

/**
 * 复制编辑器内容到剪贴板
 * @param {string} editorType - 编辑器类型
 */
function copyEditorContent(editorType) {
    let content;
    
    if (editorType === 'compose') {
        content = composeEditor.getValue();
    } else if (editorType === 'dockerfile') {
        content = dockerfileEditor.getValue();
    } else if (editorType === 'nginx') {
        content = nginxEditor.getValue();
    }
    
    navigator.clipboard.writeText(content).then(() => {
        showNotification('内容已复制到剪贴板');
    }).catch(err => {
        console.error('复制失败:', err);
        showNotification('复制失败，请手动复制', 'error');
    });
}

/**
 * 清除编辑器内容
 * @param {string} editorType - 编辑器类型
 */
function clearEditorContent(editorType) {
    let editor;
    if (editorType === 'compose') {
        editor = composeEditor;
    } else if (editorType === 'dockerfile') {
        editor = dockerfileEditor;
    } else if (editorType === 'nginx') {
        editor = nginxEditor;
    }
    
    if (!editor) return;
    
    if (confirm('确定要清除当前编辑器的所有内容吗？')) {
        editor.setValue('');
        saveEditorContentToStorage(editorType, '');
        editor.focus();
        showNotification('内容已清除');
    }
}

/**
 * 保存编辑器内容到文件
 * @param {string} editorType - 编辑器类型
 */
function saveEditorContent(editorType) {
    let editor, fileName;
    if (editorType === 'compose') {
        editor = composeEditor;
        fileName = 'docker-compose.yml';
    } else if (editorType === 'dockerfile') {
        editor = dockerfileEditor;
        fileName = 'Dockerfile';
    } else if (editorType === 'nginx') {
        editor = nginxEditor;
        fileName = 'nginx.conf';
    }
    
    if (!editor) return;
    
    const content = editor.getValue();
    const blob = new Blob([content], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    
    const a = document.createElement('a');
    a.href = url;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    
    setTimeout(() => {
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }, 100);
    
    showNotification(`文件已保存为 ${fileName}`);
}

/**
 * 渲染所有模板
 */
function renderTemplates() {
    // 渲染 Docker Compose 模板
    let composeHtml = '';
    for (const category in composeTemplateCategories) {
        composeHtml += `<div class="template-category">
            <h3><i class="${composeTemplateCategories[category].icon}"></i> ${category}</h3>`;
        
        composeTemplateCategories[category].templates.forEach(templateKey => {
            const template = templates.compose[templateKey];
            composeHtml += `<button class="template-btn" data-type="compose" data-template="${templateKey}">
                <i class="${template.icon}"></i> ${template.name}
            </button>`;
        });
        
        composeHtml += '</div>';
    }
    composeTemplatesContainer.innerHTML = composeHtml;
    
    // 渲染 Dockerfile 模板
    let dockerfileHtml = '';
    for (const category in dockerfileTemplateCategories) {
        dockerfileHtml += `<div class="template-category">
            <h3><i class="${dockerfileTemplateCategories[category].icon}"></i> ${category}</h3>`;
        
        dockerfileTemplateCategories[category].templates.forEach(templateKey => {
            const template = templates.dockerfile[templateKey];
            dockerfileHtml += `<button class="template-btn" data-type="dockerfile" data-template="${templateKey}">
                <i class="${template.icon}"></i> ${template.name}
            </button>`;
        });
        
        dockerfileHtml += '</div>';
    }
    dockerfileTemplatesContainer.innerHTML = dockerfileHtml;
    
    // 渲染 Nginx 模板
    let nginxHtml = '';
    for (const category in nginxTemplateCategories) {
        nginxHtml += `<div class="template-category">
            <h3><i class="${nginxTemplateCategories[category].icon}"></i> ${category}</h3>`;
        
        nginxTemplateCategories[category].templates.forEach(templateKey => {
            const template = templates.nginx[templateKey];
            nginxHtml += `<button class="template-btn" data-type="nginx" data-template="${templateKey}">
                <i class="${template.icon}"></i> ${template.name}
            </button>`;
        });
        
        nginxHtml += '</div>';
    }
    nginxTemplatesContainer.innerHTML = nginxHtml;
    
    // 渲染参数
    composeParametersContainer.innerHTML = composeParameters;
    dockerfileParametersContainer.innerHTML = dockerfileParameters;
    nginxParametersContainer.innerHTML = nginxParameters;
}

/**
 * 切换壁纸
 */
function changeWallpaper() {
    currentWallpaperIndex = (currentWallpaperIndex + 1) % wallpapers.length;
    
    document.body.style.backgroundImage = wallpapers[currentWallpaperIndex];
    document.body.style.backgroundSize = 'cover';
    document.body.style.backgroundRepeat = 'no-repeat';
    document.body.style.backgroundPosition = 'center center';
    
    localStorage.setItem('wallpaperIndex', currentWallpaperIndex);
    
    showNotification('壁纸已更换');
}

/**
 * 处理编辑器操作按钮点击
 * @param {string} action - 操作类型
 * @param {string} editorType - 编辑器类型
 */
function handleEditorAction(action, editorType) {
    switch(action) {
        case 'clear':
            clearEditorContent(editorType);
            break;
        case 'save':
            saveEditorContent(editorType);
            break;
        case 'copy':
            copyEditorContent(editorType);
            break;
    }
}

/**
 * 初始化事件监听器
 */
function initEventListeners() {
    // 视图切换
    viewTabs.forEach(tab => {
        tab.addEventListener('click', () => {
            switchView(tab.dataset.view);
        });
    });
    
    // 编辑器操作按钮点击事件
    editorActionButtons.forEach(btn => {
        btn.addEventListener('click', () => {
            handleEditorAction(btn.dataset.action, btn.dataset.editor);
        });
    });
    
    // 模板按钮点击 (使用事件委托)
    document.addEventListener('click', (e) => {
        if (e.target.classList.contains('template-btn')) {
            showTemplatePreview(
                e.target.dataset.type,
                e.target.dataset.template
            );
        }
        
        // 参数按钮点击
        if (e.target.classList.contains('param-btn')) {
            addParameterToEditor(e.target.dataset.command);
        }
    });
    
    // 模板预览操作
    cancelPreviewBtn.addEventListener('click', () => {
        templatePreview.classList.remove('active');
        currentTemplate = null;
    });
    
    applyTemplateBtn.addEventListener('click', applyTemplate);
    
    // 主题切换
    themeSwitcher.addEventListener('click', () => {
        if (body.classList.contains('dark-mode')) {
            body.classList.remove('dark-mode');
            body.classList.add('light-mode');
            localStorage.setItem('theme', 'light-mode');
            updateThemeButton('light-mode');
            
            const editorTheme = 'default';
            if (composeEditor) composeEditor.setOption('theme', editorTheme);
            if (dockerfileEditor) dockerfileEditor.setOption('theme', editorTheme);
            if (nginxEditor) nginxEditor.setOption('theme', editorTheme);
        } else {
            body.classList.remove('light-mode');
            body.classList.add('dark-mode');
            localStorage.setItem('theme', 'dark-mode');
            updateThemeButton('dark-mode');
            
            const editorTheme = 'dracula';
            if (composeEditor) composeEditor.setOption('theme', editorTheme);
            if (dockerfileEditor) dockerfileEditor.setOption('theme', editorTheme);
            if (nginxEditor) nginxEditor.setOption('theme', editorTheme);
        }
    });
    
    // 壁纸切换
    changeWallpaperBtn.addEventListener('click', changeWallpaper);
    
    // 页面关闭前保存内容
    window.addEventListener('beforeunload', () => {
        if (composeEditor) {
            saveEditorContentToStorage('compose', composeEditor.getValue());
        }
        if (dockerfileEditor) {
            saveEditorContentToStorage('dockerfile', dockerfileEditor.getValue());
        }
        if (nginxEditor) {
            saveEditorContentToStorage('nginx', nginxEditor.getValue());
        }
    });
}

/**
 * 初始化应用
 */
function initApp() {
    renderTemplates();
    initCodeEditors();
    initTheme();
    initWallpaper();
    initEventListeners();
    // 初始化开屏动画
    initSplashScreen();
    
    setTimeout(() => {
        if (composeEditor) {
            composeEditor.focus();
        }
    }, 500);
}

// 添加开屏动画控制函数
function initSplashScreen() {
    const splashScreen = document.getElementById('splash-screen');
    
    // 1.5秒后开始关闭动画（原为3秒）
    setTimeout(() => {
        splashScreen.classList.add('splash-screen-hidden');
        
        // 动画结束后移除元素
        setTimeout(() => {
            splashScreen.remove();
        }, 1000);
    }, 600); // 开屏时间
}

// 当页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', initApp);